using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Sustainalytics.Auth.Claims;

namespace Sustainalytics.Claims
{
    public class UniverseCheckerAttribute : ActionFilterAttribute
    {
        private readonly string _parameterName;
        private AccountFeature _featureName;

        public UniverseCheckerAttribute(string parameterName, AccountFeature featureName=AccountFeature.EsgRatingsOnlineReport)
        {
            _parameterName = parameterName;
            _featureName = featureName;

        }

        /// <exception cref="ArgumentException">No OWIN context found.</exception>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
          
            var owinContext = actionContext.Request.GetOwinContext();

            if (owinContext == null)
                throw new ArgumentException("No OWIN context found.");

            var claimsPrincipal = actionContext.Request.GetOwinContext().Authentication.User;

            if (claimsPrincipal == null || !claimsPrincipal.Identity.IsAuthenticated)
                return;


            //get the parameters from query string
            var queryString = actionContext.Request.GetQueryNameValuePairs().ToList();

            if (queryString.Any())
            {
                var featureKvp = queryString.FirstOrDefault(x => x.Key.Contains("feature"));
                if (!featureKvp.Equals(default(KeyValuePair<string, string>)))
                {
                    if (!Enum.TryParse(featureKvp.Value, out _featureName))
                    {
                        _featureName = AccountFeature.EsgRatingsOnlineReport;
                    }
                }
            }

            var userUniverseIds = claimsPrincipal.Claims.GetUniverseIds(_featureName);

            actionContext.ActionArguments[_parameterName] = userUniverseIds.ToArray();
        }
    }
}